package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 根据id扣减余额
     *
     * @param id
     * @param money
     */
    @Override
    public void deductBalanceById(Long id, Integer money) {
        //判断用户是否存在
        User user = getById(id);
        if (user == null || user.getStatus() == 2) {
            throw new RuntimeException("用户状态异常");
        }
        //判断用户余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        //扣减余额
        int reBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, reBalance)
                .set(reBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//乐观锁
                .update();
//        baseMapper.deductBalanceById(id, money);
    }

    /**
     * 查询用户列表
     */
    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }
}
